
function setMainImage(item) {
	var mainImage = document.getElementById('main-image');
	var img = mainImage.children[0].children[0];
	img.setAttribute('src', item.url);
	
	var table = mainImage.children[1].children[0];
	table.innerHTML = '					\
		<tr>							\
			<td>Title:</td>				\
			<td>' + item.title + '</td>	\
		</tr>							\
		<tr>							\
			<td>Rating:</td>			\
			<td>' + item.rating + '</td>\
		</tr>							\
		<tr>							\
			<td>Tags:</td>				\
			<td>' + item.tags + '</td>	\
		</tr>							\
		<tr>							\
			<td>Uploader:</td>			\
			<td>' + item.user + '</td>	\
		</tr>';
}

function viewImageOnClick(event) {
	var url = event.target.getAttribute('src');
	for (var i=0; i < imageList.length; i++) {
		var item = imageList[i];
		if (item.url === url) {
			setMainImage(item);
		}
	}
}

function changeCategory(event) {
	if (this.value === 'all') {
		window.location = 'browser.jsp';
	}
	else {
		window.location = 'browser.jsp?tag=' + this.value;
	}
}

function populateThumbTable() {
	var thumbTable = document.getElementById('thumb-table');
	var newHTML = '';
	for (var i=0; i < imageList.length; i++) {
		var image = imageList[i];
		newHTML += '<td><div class="image-holder"><img src="' + image.url + '" class="thumb"></div></td>';
	}
	
	if (imageList.length == 10) {
		if (tag !== null) {
			newHTML += '<td><a href="browser.jsp?tag=' + tag  + '"><div id="next-button"></div></a>';
		}
		else {
			newHTML += '<td><a href="browser.jsp"><div id="next-button"></div></a>';
		}
	}
	thumbTable.innerHTML = newHTML;
}

window.onload = function(event) {
	setMainImage(imageList[0]);
	
	var dropdown = document.getElementById('category-select');
	dropdown.onchange = changeCategory;
	if (tag) {
		dropdown.value = tag;
	}
	
	populateThumbTable();
	var thumbs = document.getElementsByClassName('thumb');
	for (var i=0; i < thumbs.length; i++) {
		thumbs[i].onclick = viewImageOnClick;
	}
}